package com.app.couponsharelife.ui.main.tribe.checkin

import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.hwangjr.rxbus.RxBus
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.PageTipBean
import com.app.couponsharelife.data.bean.SignInfoBean
import com.app.couponsharelife.databinding.FragmentSortBinding
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.adapter.CouponDiamondRankAdapter
import com.app.couponsharelife.ui.dialog.CheckInSuccessDialog
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.ui.viewmodel.TribeViewModel
import com.app.couponsharelife.utils.AppUtils
import com.app.fuquan.data.bean.PageStatus
import kotlinx.android.synthetic.main.activity_check_in.*
import java.text.DecimalFormat
import java.util.*

class CheckInActivity : BaseActivity() {

    override val viewLayoutId: Int get() = R.layout.activity_check_in

    private var mViewModel: TribeViewModel? = null

    private var index = 1

    override fun initViews() {
        ivBack.setOnClickListener { finish() }
        clCheckInBtn.setOnClickListener {
            if (tvCheckIn.text == "已签到") {
                showToastMsg("您今天已签到")
                return@setOnClickListener
            }
            userSign()
        }
    }

    private fun initRecyclerView(list: List<SignInfoBean.UsersBean>) {
        val data = mutableListOf<Any>()
        if (list.isEmpty()) {
            data.add(PageTipBean("暂无排名", R.drawable.ic_data_empty, 1))
        } else {
            data.add("")
            data.addAll(list)
        }
        mRecyclerView.layoutManager = LinearLayoutManager(this)
        mRecyclerView.adapter = CouponDiamondRankAdapter(data, object : OnClickListener {
            override fun click(arg1: Int, arg2: Any) {

            }
        })
    }

    override fun initViewModel() {
        if (mViewModel == null) mViewModel = ViewModelProviders.of(this).get(TribeViewModel::class.java)
        if (!mViewModel!!.getUserSignInfo()!!.hasObservers()) {
            mViewModel!!.getUserSignInfo()!!.observe(this, Observer {
                if (it == null) {
                    dismissProgressDialog()
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                        showProgressDialog("请稍候")
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.refreshGetUserSignInfo(hashMapOf(), false)
                        showToastMsg(parseErrorDate(it.error!!.message).tip)
                    }
                    PageStatus.Empty -> {
                        dismissProgressDialog()
                        mViewModel!!.refreshGetUserSignInfo(hashMapOf(), false)
                        showToastMsg("暂无数据")
                    }
                    PageStatus.Content -> {
                        dismissProgressDialog()
                        RxBus.get().post("freshCouponKing","")
                        mViewModel!!.refreshGetUserSignInfo(hashMapOf(), false)
                        if (it.data!!.code == 200 && it.data.data != null) {
                            val df = DecimalFormat("#0")
                            tvCheckInNum.text = df.format(it.data.data!!.couponForce.toDouble())
                            if (it.data.data!!.lastSignInDay!=null) {
                                if (it.data.data!!.lastSignInDay!!.length > 10 &&
                                        AppUtils.getCurrentTime2() == it.data.data!!.lastSignInDay!!.substring(0, 10)) {
                                    tvCheckIn.text = "已签到"
                                } else {
                                    tvCheckIn.text = "点击签到"
                                }
                            }
                            val images = arrayOf(ivCheckInImage1, ivCheckInImage2, ivCheckInImage3, ivCheckInImage4, ivCheckInImage5, ivCheckInImage6, ivCheckInImage7)
                            val texts = arrayOf(tvCheckIn1, tvCheckIn2, tvCheckIn3, tvCheckIn4, tvCheckIn5, tvCheckIn6, tvCheckIn7)
                            val indicators = arrayOf(mIndicatorView1, mIndicatorView2, mIndicatorView3, mIndicatorView4, mIndicatorView5, mIndicatorView6)
                            index = it.data.data!!.continuousDay + 1
                            index = if (index > 7) 7 else index
                            val count = if (it.data.data!!.continuousDay > 7) 7 else it.data.data!!.continuousDay
                            for (i in 0 until count) {
                                images[i].setImageResource(R.drawable.ic_act_check_in_true)
                                texts[i].setTextColor(ContextCompat.getColor(this, R.color.act_check_in_text_color))
                                if (i >= 1) {
                                    indicators[i - 1].setBackgroundColor(ContextCompat.getColor(this, R.color.act_check_in_record_indicator_true_color))
                                }
                            }
                            if (count < 7) {
                                for (i in count until 7) {
                                    images[i].setImageResource(R.drawable.ic_act_check_in_false)
                                    texts[i].setTextColor(ContextCompat.getColor(this, R.color.act_welcome_indicator_no_select_bg_color))
                                    if (i >= 1) {
                                        indicators[i - 1].setBackgroundColor(ContextCompat.getColor(this, R.color.act_check_in_record_indicator_false_color))
                                    }
                                }
                            }
                            initRecyclerView(it.data.data!!.users)
                        } else {
                            showToastMsg("请求失败")
                        }
                    }
                }
            })
            mViewModel!!.userSign()!!.observe(this, Observer {
                if (it == null) {
                    dismissProgressDialog()
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                        showProgressDialog("请稍候")
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.refreshUserSign(hashMapOf(), false)
                        showToastMsg(parseErrorDate(it.error!!.message).tip)
                    }
                    PageStatus.Empty -> {
                        dismissProgressDialog()
                        mViewModel!!.refreshUserSign(hashMapOf(), false)
                        showToastMsg("暂无数据")
                    }
                    PageStatus.Content -> {
                        dismissProgressDialog()
                        mViewModel!!.refreshUserSign(hashMapOf(), false)
                        if (it.data!!.code == 200) {
                            CheckInSuccessDialog(this, R.style.DialogStyle, index).show()
                            getUserSignInfo()
                        } else {
                            (mViewDataBinding as FragmentSortBinding).pageTipBean = parseErrorDate("请求失败")
                        }
                    }
                }
            })
        }
        getUserSignInfo()
    }

    private fun getUserSignInfo() {
        val map = HashMap<String, String>()
        map["userId"] = AppUtils.getString(Contacts.USERID, "")
        mViewModel?.refreshGetUserSignInfo(map, true)
    }

    private fun userSign() {
        val map = HashMap<String, String>()
        map["userId"] = AppUtils.getString(Contacts.USERID, "")
        mViewModel?.refreshUserSign(map, true)
    }
}
